package logic

import (
	"context"
	"errors"
	"novel-sys/cache"
	"novel-sys/model/mysql"

	"novel-sys/goods/goods"
	"novel-sys/goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordUpdateLogic {
	return &PasswordUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordUpdateLogic) PasswordUpdate(in *goods.PasswordUpdateRequest) (*goods.PasswordUpdateResponse, error) {
	// todo: add your logic here and delete this line
	data := mysql.User{
		Mobile:   in.Mobile,
		Password: in.NewPassword,
	}
	get, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Result()
	if in.Sms != get {
		return nil, errors.New("验证码错误")
	}
	cache.Rdb.Del(l.ctx, "SendSms"+in.Mobile)
	cache.Rdb.Del(l.ctx, "SendSms1"+in.Mobile)
	var user mysql.User
	if err := user.UserByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	if user.Password != in.OldPassword {
		return nil, errors.New("旧密码错误")
	}

	if err := data.UpdatePassword(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	return &goods.PasswordUpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
